# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2018/6/18 10:02
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : func.py
# @Software   : PyCharm
# -----------------------------------------

"""
return_type_sql:
    0：0                        # 原始的对比结果，包含状态
    1: sql                      # 原始的对比sql结果
    2: no_drop                  # 去掉drop语句的结果
    3: no_index                 # 去掉index的结果
    4: no_drop_and_index        # 去掉drop和index结果
    5: no_drop_and_index_and_id # 去掉drop、index、id
"""
from utils.decorator import check_conn, check_src_dest, record_api_log
from diff.sh_tools import get_diff_sql
from utils.mysql import Mysql


def diff_table(src, dest, return_type):
    infos = {
        "status": False,
        "data": None
    }
    if src['table'] is None or dest['table']:
        infos["msg"] = f"table is not set or table is None, please check it!"
        return infos
    if check_db_table(src, src.get("database"), src.get('table')):
        if check_db_table(dest, dest.get("database"), dest.get('table')):
            status, diffsql = diff_sql(src, dest, return_type)
            if not status:
                if "Success. All objects are the same" in diffsql:
                    infos["data"] = "Success. All objects are the same"
                    infos["msg"] = "Success. All objects are the same"
                else:
                    infos["data"] = diffsql
                    infos["msg"] = "could not get diff sql, please manual check it"
            else:
                infos["status"] = True
                infos["data"] = diffsql
        else:
            infos["msg"] = f"{dest} {dest.get('database')} not found table: {dest.get('table')}"
    else:
        infos["msg"] = f"{src} {src.get('database')} not found table: {src.get('table')}"

    return infos



def diff_database(src, dest, return_type):
    infos = {
        "status": False,
        "data": {},
        "failed": {},
        "src_surplus": None,
        "dest_surplus": None,
        "intersection": None
    }
    src_tables = set(Mysql(src).get_tables(src.get('database')))
    dest_tables = set(Mysql(dest).get_tables(dest.get('database')))

    intersection = src_tables & dest_tables
    infos["intersection"] = list(intersection)
    infos["src_surplus"] = list(src_tables - intersection)
    infos["dest_surplus"] = list(dest_tables - intersection)

    for table in intersection:
        status, diffsql = diff_sql(src, dest, return_type)
        if status:
            infos["data"][table] = diffsql
        else:
            if "Success. All objects are the same" not in diffsql:
                infos["failed"][table] = diffsql
    else:
        infos["status"] = True

    return infos



def get_diff_database_info(src, dest):
    infos = {
        "status": False,
        "data": None,
        "src_surplus": None,
        "dest_surplus": None,
        "intersection": None
    }
    src_tables = set(Mysql(src).get_tables(src.get("database")))
    dest_tables = set(Mysql(dest).get_tables(dest.get("database")))

    intersection = src_tables & dest_tables
    infos["intersection"] = list(intersection)
    infos["src_surplus"] = list(src_tables - intersection)
    infos["dest_surplus"] = list(dest_tables - intersection)
    infos["status"] = True
    return infos


def check_db_table(conn, database, table):
    dbop = Mysql(conn)
    return dbop.check_table(database, table)

@record_api_log
def diff_sql(src, dest, return_type=1):
    infos = {
        "status": False,
        "data": "",
        "msg": ""
    }
    diff_info = get_diff_sql(src, dest)
    status = diff_info.get("status")
    diffsql = diff_info.get("data")
    infos["data"] = diffsql
    if not status:
        # 没有差异 返回Success. All objects are the same
        infos["msg"] = "Success. All objects are the same"
        return infos
        # return False, diffsql
    else:
        # 对比失败，没有生成语句
        if "# Cannot generate ALTER statement" in diffsql:
            infos["msg"] = "Cannot generate ALTER statement"
            # return False, diffsql
            return infos
        # 生成语句
        tag = True
        if return_type == 1:
            tag, mydiffsql = return_type_sql(diffsql)
        elif return_type == 2:
            tag, mydiffsql = return_type_no_drop(diffsql)
        elif return_type == 3:
            tag, mydiffsql = return_type_no_index(diffsql)
        elif return_type == 4:
            tag, mydiffsql = return_type_no_drop_and_index(diffsql)
        elif return_type == 5:
            tag, mydiffsql = return_type_no_drop_and_index_and_id(diffsql)
        else:
            mydiffsql = diffsql
        sql = mydiffsql.replace("\'\'", "\'").rstrip()
        if sql.endswith(","):
            my_sql = f"{sql[0:-1]};"
        else:
            if sql.endswith(";"):
                my_sql = sql
            else:
                my_sql = f"{sql};"
        if my_sql.endswith('`;'):
            infos["status"] = False
            infos["msg"] = "Success. All objects are the same"
            return infos

        infos["status"] = tag
        infos["data"] = my_sql
        return infos


def return_type_no_drop_and_index_and_id(diffsql):
    tag = False
    temp = []
    for line in diffsql.split('\n'):
        if line.startswith("ALTER TABLE"):
            tag = True
        if line.startswith("  ADD INDEX") or line.startswith("  ADD UNIQUE INDEX") or line.startswith(
                "  DROP") or line.startswith("  CHANGE COLUMN id "):
            continue
        if line.endswith(';'):
            temp.append(line)
            break
        if "Compare failed." in line:
            break
        if tag:
            temp.append(line.replace("DEFAULT ' COMMENT", "DEFAULT '' COMMENT"))
    mydiffsql = " ".join(temp)
    return True, mydiffsql


def return_type_no_drop_and_index(diffsql):
    tag = False
    temp = []
    for line in diffsql.split('\n'):
        if line.startswith("ALTER TABLE"):
            tag = True
        if line.startswith("  ADD INDEX") or line.startswith("  DROP") or line.startswith("  ADD UNIQUE INDEX"):
            continue
        if line.endswith(';'):
            temp.append(line)
            break
        if "Compare failed." in line:
            break
        if tag:
            temp.append(line.replace("DEFAULT ' COMMENT", "DEFAULT '' COMMENT"))
    mydiffsql = " ".join(temp)
    return True, mydiffsql


def return_type_no_index(diffsql):
    tag = False
    temp = []
    for line in diffsql.split('\n'):
        if line.startswith("ALTER TABLE"):
            tag = True
        if line.startswith("  ADD INDEX") or line.startswith("  DROP INDEX") or line.startswith("  ADD UNIQUE INDEX"):
            continue
        if line.endswith(';'):
            temp.append(line)
            break
        if "Compare failed." in line:
            break
        if tag:
            temp.append(line.replace("DEFAULT ' COMMENT", "DEFAULT '' COMMENT"))
    mydiffsql = " ".join(temp)
    return True, mydiffsql


def return_type_no_drop(diffsql):
    tag = False
    temp = []
    for line in diffsql.split('\n'):
        if line.startswith("ALTER TABLE"):
            tag = True
        if line.startswith("  DROP"):
            continue
        if line.endswith(';'):
            temp.append(line)
            break
        if "Compare failed." in line:
            break
        if tag:
            temp.append(line.replace("DEFAULT ' COMMENT", "DEFAULT '' COMMENT"))
    mydiffsql = " ".join(temp)
    return True, mydiffsql


def return_type_sql(diffsql):
    tag = False
    temp = []
    for line in diffsql.split('\n'):
        if line.startswith("ALTER TABLE"):
            tag = True
        if line.endswith(';'):
            temp.append(line)
            break
        if tag:
            temp.append(line.replace("DEFAULT ' COMMENT", "DEFAULT '' COMMENT"))
    mydiffsql = " ".join(temp)
    return True, mydiffsql
